package servlet.good;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import beans.Goods;
import service.GoodService;

@WebServlet("/GoodsOperationServlet")
public class GoodsOperationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public GoodsOperationServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		GoodService service = new GoodService();
		
		String operation = request.getParameter("operation");
		String sid = request.getParameter("sid");
		String gid = request.getParameter("gid");
		String name = request.getParameter("name");
		String price = request.getParameter("price");
		String classify = request.getParameter("classify");
		String stock = request.getParameter("stock");
		String sales = request.getParameter("sales");
		String goodDescribe = request.getParameter("goodDescribe");
		String status = request.getParameter("status");
		String id = request.getParameter("id");
		
		switch(operation) {
		case "del":
			service.deleteById(id);
			break;
		case "alt": 
			if (id != null) {
				Goods good = service.getGoodsById(id);
				request.setAttribute("operation", "alt");
				request.setAttribute("goods", good);
				request.getRequestDispatcher("/admin/goodinfo.jsp").forward(request, response);
				return;
			}
			
			service.alterGood(gid, name, price, classify, stock, sales, goodDescribe, status);
			response.sendRedirect("GoodServlet?id=" + sid);
			break;
		case "add": 
			if (name != null && !name.equals("")) {
				service.addGood(sid, name, price, classify, stock, sales, goodDescribe, status);
				response.sendRedirect("GoodServlet?id=" + sid);
			}else {
				request.setAttribute("operation", "add");
				request.setAttribute("sid", sid);
				request.getRequestDispatcher("/admin/goodinfo.jsp").forward(request, response);
			}
			break;
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
